<?php

namespace App\Http\Controllers\RbhMiniProgram;

use App\Models\AsyncEventModel;
use App\Models\GoodsPicModel;
use App\Models\GoodsSpecModel;
use App\Models\Jst\PicInfoModel;
use App\Models\RdsUserStoreModel;
use App\Utils\ApiResponse;
use App\Utils\ResponseEnum;
use App\Utils\VerifyRequestInput;
use App\Exceptions\BusinessException;
use App\Http\Controllers\Controller;
use App\Models\GoodsPicPrimaryModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class MiniProgramGoodsController extends Controller
{
    use ApiResponse, VerifyRequestInput;

    private int $SSVip = 177;

    public function getList()
    {

    }

    /**
     * 获取供应商商品列表
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getSupplyGoodsList(Request $request): JsonResponse
    {
        $sid = $this->verifyId('sid');
        $pageSize = $request->input('pageSize', 10);
        $paginate = GoodsPicPrimaryModel::where('PStatus', 0)->where('SID', $sid)
            ->orderByDesc('AllID')->orderByDesc('ITime')->paginate($pageSize);
        return $this->success($paginate);
    }

    /**
     * 获取商品详情
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getGoodsInfo(Request $request): JsonResponse
    {
        $goodsId = $this->verifyId('goods_id');
        $goods = GoodsPicPrimaryModel::where('ID', $goodsId)->select(['ID', 'SID', 'SName', 'Path', 'PName', 'FName', 'Type', 'IsEncry', 'IsPaid', 'ToySn', 'PHotNum', 'ITime', 'skuFlag', 'ali_url'])->first();
        if (!$goods)
            return $this->fail(ResponseEnum::CLIENT_DELETED_ERROR);
        $collection = GoodsPicModel::where('ID', $goodsId)->orWhere('PID', $goodsId)->select(['ID', 'PID', 'Path', 'FName', 'IsEncry', 'IsVideo'])->get();
        $goods->tops = $this->getTopImageOrVideoList($goods, $collection);
        $goods->images = $this->getImagesList($collection);
        $specCollection = $this->getGoodsSpecList($goods);
        $goods->specs = $specCollection;
        $goods->price = $specCollection->min('price');
        $goods->min_weight = $specCollection->min('weight');
        $goods->stock = '> 1';
        $goods->cate = $this->getGoodsTypeText($goods->Type);
        $goods->size = DB::connection('rbh')->table('pic_gg')->where('PID', $goodsId)->value('ToySize');
        $goods->is_store = $request->input('uid') ? (RdsUserStoreModel::where('uid', $request->input('uid'))->where('goods_id', $goodsId)->value('ID') ? 1 : 0) : 0;
        return $this->success($goods);
    }

    /**
     * 更新商品下载数量
     * @return JsonResponse
     * @throws BusinessException
     */
    public function updateGoodsBuyNum(): JsonResponse
    {
        $goodsId = $this->verifyId('goods_id');
        AsyncEventModel::create(['event' => 'inc', 'table' => 'pic', 'pid' => $goodsId]);
        return $this->success();
    }

    /**
     * 获取置顶图数据
     * @param $goods
     * @param $collection
     * @return array
     */
    private function getTopImageOrVideoList($goods, $collection): array
    {
        if ($collection->isEmpty())
            return [];
        $images = $this->getTopImageList($goods);
        $images = $images ?: $this->getDefaultTopImageList($collection);
        $video = $this->getVideo($goods, $collection);
        return $video ? array_merge([$video], $images) : $images;
    }

    /**
     * 获取置顶图
     * @param $goods
     * @return null
     */
    private function getTopImageList($goods)
    {
        $collection = PicInfoModel::where('pid', $goods->ID)->where('pic_id', '!=', $goods->ID)->where('type', 1)
            ->where('width', '>', 0)->whereRaw('width = height')->select(['pic_id', 'type', 'file_url as url', 'width', 'height'])
            ->orderByDesc('pic_id')->limit(5)->get();
        return $collection->isEmpty() ? null : $collection->all();
    }

    /**
     * 获取默认置顶图
     * @param $collection
     * @return mixed
     */
    private function getDefaultTopImageList($collection): mixed
    {
        return $collection->where('IsVideo', 0)->sortBy('ID', SORT_DESC)->take(5)->transform(function ($item) {
            return [
                'pic_id'    => $item->ID,
                'type'      => 1,
                'url'       => Controller::getImageFullUrl($item, $item->isEncry === 0),
                'width'     => $item->IsEncry > 0 ? 800 : 280,
                'height'    => $item->IsEncry > 0 ? 800 : 280
            ];
        })->all();
    }

    /**
     * 获取视频数据
     * @param $goods
     * @param $collection
     * @return array|null
     */
    private function getVideo($goods, $collection): ?array
    {
        $video = $collection->where('IsVideo', 1)->first();
        if (!$video)
            return null;
        return  [
            'type'      => 2,
            'poster'    => Controller::getImageFullUrl($goods, $goods->isEncry === 0),
            'url'      => Controller::getImageFullUrl($video),
        ];
    }

    /**
     * 获取图片列表
     * @param $collection
     * @return mixed
     */
    private function getImagesList($collection): mixed
    {
        if ($collection->isEmpty())
            return [];
        $images = $collection->where('IsVideo', 0)->transform(function ($item) {
            return ['ID' => $item->ID, 'url' => Controller::getImageFullUrl($item, $item->isEncry === 0)];
        })->all();
        $ids = array_column($images, 'ID');
        array_multisort($ids, SORT_DESC, $images);
        return $images;
    }

    /**
     * 获取商品规格列表
     * @param $goods
     * @return mixed
     */
    private function getGoodsSpecList($goods): mixed
    {
        $showPrivate = request()->input('uid', 0) == $this->SSVip ? 1 : 0;
        return GoodsSpecModel::where('goods_id', $goods->ID)->where('private', '<=', $showPrivate)
            ->select(['id', 'sid', 'goods_id', 'goods_sn', 'color', 'size', 'weight', 'price', 'stock', 'thumbnail'])
            ->get();
    }

    /**
     * 获取方图数据
     * @param $item
     * @return array
     */
    private function getImageItemData($item): array
    {
        return [
            'type'  => 1,
            'file'  => Controller::getImageFullUrl($item),
            'width' => $item->IsEncry > 0 ? 800 : 280,
            'height'=> $item->IsEncry > 0 ? 800 : 280
        ];
    }

    /**
     * 获取视频数据
     * @param $item
     * @param $goods
     * @return array
     */
    private function getVideoItemData($item, $goods): array
    {
        return [
            'type' => 2,
            'poster' => Controller::getImageFullUrl($goods),
            'file' => Controller::getImageFullUrl($item),
        ];
    }

    /**
     * 获取商品类型
     * @param $type
     * @return array
     */
    private function getGoodsTypeText($type): array
    {
        $array = array_values(array_filter(explode('|', $type), function ($value) {
            return intval($value) > 6;
        }));
        $collection = $this->getGoodsTypeCollection();
        if (!empty($array) && count($array) > 0) {
            $cateId = $array[0];
            $cate = $collection->where('ID', $cateId)->first();
            if (!$cate)
                return $this->getNoParentCateData($type);
            else {
                $parent = $collection->where('ID', $cate->MID)->first();
                return [
                    'id'        => $parent ? $parent->ID : 1,
                    'name'      => $parent ? $parent->TName : '毛绒玩具',
                    'children'  => [
                        'id'    => $cate->ID,
                        'name'  => $cate->TName
                    ]
                ];
            }
        }
    }

    /**
     * 获取没有父级分类的商品类型
     * @param $type
     * @return array
     */
    private function getNoParentCateData($type): array
    {
        $array = array_values(array_filter(explode('|', $type), function ($value) {
            return intval($value) > 0;
        }));
        $text = ['id' => 1, 'name' => '毛绒玩具'];
        $collection = $this->getGoodsTypeCollection();
        if (count($array))  {
            $cate = $collection->where('ID', $array[0])->first();
            $text['children'] = ['id' => $cate ? $cate->ID : 1, 'name' => $cate ? $cate->TName : '毛绒玩具'];
        } else
            $text['children'] = ['id' => 1, 'name' => '毛绒玩具'];
        return $text;
    }

    /**
     * 获取商品类型列表
     * @return mixed
     */
    private function getGoodsTypeCollection(): mixed
    {
//        if (!Cache::has('goodsTypeCollection'))
            Cache::put('goodsTypeCollection', DB::connection('rbh')->table('pic_type')->select(['ID', 'MID', 'TName'])->get());
        return Cache::get('goodsTypeCollection');
    }
}
